package com.dlyk;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;

// mapper包下的接口没有使用注解，所以需要扫描识别
@MapperScan(basePackages = {"com.dlyk.mapper"})
@SpringBootApplication
public class DlykServerApplication implements CommandLineRunner {

    // Redis模板类
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    // 用于接收写入到内存的数据
    public static final Map<String, Object> cacheMap = new HashMap<>();

    public static void main(String[] args) {

        // 应用启动之后，获取配置应用上下文对象
        ConfigurableApplicationContext context = SpringApplication.run(DlykServerApplication.class, args);

        // 通过上下文获取线程池Bean的名字
        String[] beanNamesForType = context.getBeanNamesForType(Executor.class);
        for (String s : beanNamesForType) {
            // applicationTaskExecutor（Spring Boot内置的线程池，IOC容器中已经创建好了该线程池，可以直接注入使用）
            System.out.println(s);
        }

        // 通过Bean的名字获取线程池对象
        Object applicationTaskExecutor = context.getBean("applicationTaskExecutor");
        // org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor@5d7a5752
        System.out.println(applicationTaskExecutor);
    }

    @Override
    public void run(String... args) throws Exception {

        // Spring Boot项目启动后，把RedisTemplate这个Bean修改一下，修改key和value的序列化方式

        // 设置key序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        // 对象映射工具，Java对象 和 json对象进行相互转化
        ObjectMapper mapper = new ObjectMapper();
        // 设置可见性
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 激活类型
        mapper.activateDefaultTyping(mapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.EVERYTHING);

        // 设置value序列化
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Object>(mapper, Object.class));

        // 设置hashKey序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        // 设置hashValue序列化
        redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<Object>(mapper, Object.class));
    }

}

